package com.nvn.washiodriver.activities;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.nvn.washiodriver.R;
import com.nvn.washiodriver.utils.Statics;
import com.parse.LogInCallback;
import com.parse.ParseException;
import com.parse.ParseFacebookUtils;
import com.parse.ParseUser;
import com.parse.RequestPasswordResetCallback;

public class LoginActivity extends Activity implements OnClickListener {
	private Button mBtnSignIn;
	private EditText mEdtUsername, mEdtPassword;
	private TextView mTvForgotPassword;
	private ProgressDialog pd;
	private InputMethodManager imm;
	private Dialog myDialog;
	private Button myBtnForgot;
	private EditText myEdtForgot;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		overridePendingTransition(R.anim.slide_in_from_right, R.anim.anim_alpha);
		initViews();
		initProperties();
		addLitener();
	}

	public void initViews() {
		pd = new ProgressDialog(this);
		pd.setCancelable(false);
		imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);

		mBtnSignIn = (Button) findViewById(R.id.btn_sign_in);
		mEdtUsername = (EditText) findViewById(R.id.edt_email);
		mEdtPassword = (EditText) findViewById(R.id.edt_password);
		mTvForgotPassword = (TextView) findViewById(R.id.btn_fogot_password);

	}

	public void initProperties() {

	}

	public void addLitener() {
		mBtnSignIn.setOnClickListener(this);
		mTvForgotPassword.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_sign_in:
			validateAndLogin();
			break;
		case R.id.btn_fogot_password:
			showDialogForgot();
			break;
		default:
			break;
		}
	}

	private void forgotPassword() {
		String email = myEdtForgot.getText().toString().trim();
		if (email.length() == 0) {
			Statics.showToast(this, "Please enter your email");
			return;
		}

		if (!Statics.isEmailValid(email)) {
			Statics.showToast(this, "Email is invalid");
			return;
		}

		hideKeyBoard();
		myDialog.dismiss();
		pd.setMessage("Sending email...");
		pd.show();
		ParseUser.requestPasswordResetInBackground(email,
				new RequestPasswordResetCallback() {
					public void done(ParseException e) {
						pd.dismiss();
						if (e == null) {
							Statics.showToast(getBaseContext(),
									"An email was successfully sent with reset instructions.");
						} else {
							Statics.showToast(getBaseContext(),
									"Something went wrong: "+e.getMessage());
						}
					}
				});
	}

	private void validateAndLogin() {
		String username = mEdtUsername.getText().toString().trim();
		if (username.length() == 0) {
			Statics.showToast(this, "Email is required");
			return;
		}

		if (!Statics.isEmailValid(username)) {
			Statics.showToast(this, "Email is invalid");
			return;
		}

		String password = mEdtPassword.getText().toString().trim();
		if (password.length() == 0) {
			Statics.showToast(this, "Password is required");
			return;
		}

		hideKeyBoard();
		pd.setMessage("Signing in...");
		pd.show();
		ParseUser.logInInBackground(username, password, new LogInCallback() {

			@Override
			public void done(ParseUser user, ParseException arg1) {
				pd.dismiss();
				if (user != null) {
					Intent i = new Intent(LoginActivity.this,
							MainActivity.class);
					i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
					i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
					startActivity(i);
					finish();
				} else {
					Statics.showToast(getBaseContext(), "Sing in fail: "+arg1.getMessage());
				}
			}
		});
	}

	private void hideKeyBoard() {
		if (imm.isActive()) {
			imm.hideSoftInputFromWindow(mTvForgotPassword.getWindowToken(), 0); // hide
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		ParseFacebookUtils.finishAuthentication(requestCode, resultCode, data);
	}

	public void showDialogForgot() {
		myDialog = new Dialog(this);
		View view = LayoutInflater.from(this).inflate(
				R.layout.layout_forgot_password, null);
		myEdtForgot = (EditText) view.findViewById(R.id.ed_email_forgot);
		myBtnForgot = (Button) view.findViewById(R.id.btn_send);
		myDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		myDialog.setContentView(view);
		Window window = myDialog.getWindow();
		WindowManager.LayoutParams wlp = window.getAttributes();
		wlp.gravity = Gravity.CENTER;
		wlp.width = WindowManager.LayoutParams.MATCH_PARENT;
		wlp.flags &= WindowManager.LayoutParams.FLAG_DIM_BEHIND;
		window.setAttributes(wlp);
		myDialog.getWindow().setAttributes(wlp);
		myDialog.show();
		addListenerForgot();
	}

	public void addListenerForgot() {
		myBtnForgot.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				forgotPassword();
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if(ParseUser.getCurrentUser().getObjectId() != null){
			finish();
		}
	}
}
